package j20251114;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());

        // 创建多个线程同时操作列表
        List<Thread> threads = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            final int threadId = i;
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    syncList.add(threadId * 100 + j);
                }
            });
            threads.add(thread);
            thread.start();
        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            thread.join();
        }

        // 安全地迭代
        synchronized(syncList) {
            System.out.println("List size: " + syncList.size());
            for (Integer num : syncList) {
                // 处理每个元素
                System.out.println(num);
            }
        }
    }
}
